import HeaderView from "@/component/Header"
import BannerView from './component/Banner/banner'
import SwiperView from './component/Swiper/index'
import TabView from './component/Tab/index'
import TabbarView from "@/component/Tabbar"
import TimeOut from "@/component/TimeOut"
import style from './index.module.scss'
import { useEffect, useRef, useState } from "react"
import { GetHomeData } from '@/api/home'
import { swiperType } from '@/type/home'
import { ArrowDownCircleOutline } from 'antd-mobile-icons'
import { useUnactivate, useActivate } from "react-activation"

const Home = () => {
  const [swiperList, setSwiperList] = useState<swiperType[]>([])
  const [flag, setFlag] = useState(false) // 错误提示 
  const bannerSwiperRef = useRef<any>(null)
  const [backTop, setBackTop] = useState(false) // 返回顶部

  // 数据初始化  
  const init = async () => {
    const res = await GetHomeData().catch(err => {
      if (err.code === 'ECONNABORTED' || err.code === 'ERR_NETWORK') setFlag(true)
    })
    console.log(res)
    try {
      if(res?.status === 200) {
        setSwiperList(res.data.goods.data)  
      }
    } catch (error) {
      console.log(error)
    }
  }

  useEffect(() => {
    init()
    window.addEventListener('scroll', handleScroll)

    return () => { // 组件被缓存后, 不会走这个卸载组件的方法
      window.removeEventListener('scroll', handleScroll)
    }
  }, [])

  // 页面滚动监听
  const handleScroll = () => {
    try {
      const height = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
      const bannerSwiperHeight = bannerSwiperRef.current.offsetHeight
      if(height > bannerSwiperHeight) {
        setBackTop(true)
        document.getElementById('homeBox')?.getElementsByClassName('adm-tabs-header')[0].classList.add(`${style.fixed}`)
      } else {
        setBackTop(false)
        document.getElementById('homeBox')?.getElementsByClassName('adm-tabs-header')[0].classList.remove(`${style.fixed}`)
      }
    } catch (error) {
      console.log(error)
    }
  }

  useActivate(() => {
    // window.addEventListener('scroll', handleScroll)
  })

  useUnactivate(() => {
    // window.removeEventListener('scroll', handleScroll)
  })

  return (
    <>
      {/* 头部header */}
      <HeaderView title="图书兄弟" backIcon={false}/>
        
      {/* banner swiper tab   */}
      <div id='homeBox'>
       {
        swiperList.length !== 0 
        &&
        <div className={style.homeBox}>
          {/* banner和swiper */}
          <div ref={bannerSwiperRef} className={style.bannerSwiper}>
            <BannerView/>
            <SwiperView swiperList={swiperList}/>
          </div>

          {/* tab信息 */}
          <TabView></TabView>

          {/* tabbar信息 */}
          <TabbarView/>
        </div> 
       } 
      </div>
      

      {/* 错误提示页面 */}
      {flag && <TimeOut/>}

      {/* 返回顶部 */}
      {backTop && <ArrowDownCircleOutline className={style.back} onClick={() => window.scrollTo(0, 0)}/>}
    </>
  )
}

export default Home